<template>
	<view class="scrool-page">
		<view class="list-cont">
			<scroll-view class="scrool-more" style="height: 100%" scroll-y="true" scroll-with-animation="true">
				<view v-for="(item,index) in productList">
					<uni-card :title="'序号:'+(index+1)" style="background-color: darkgray;" @click="goto(item)"
						v-if="item.flag == 'true' || status=='3'">
						<text class="uni-body">托码：{{item.attr1}}</text><br>
						<text class="uni-body">箱数：{{item.boxSum}}</text><br>
					</uni-card>
					<uni-card :title="'序号:'+(index+1)" @click="goto(item)" v-else>
						<text class="uni-body">托码：{{item.attr1}}</text><br>
						<text class="uni-body">箱数：{{item.boxSum}}</text><br>
					</uni-card>
				</view>
			</scroll-view>
		</view>
		<view class="footer">
			<button type="default" size="mini" @click="reduceProduct" style="width:48%; margin-left:1%;"
				v-if='!userflag'>卸下托盘</button>
			<button type="default" size="mini" @click="reduceProduct" style="width:48%; margin-left:1%;"
				v-else>继续装车</button>
			<button type="default" size="mini" @tap="sumbit" data-target="Image"
				style="width:49%; margin-left:1%;">完成装车</button>
		</view>

		<uni-popup ref="alertDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog mode="input" title="请扫描客户手中的二维码" :value='dataValue' :before-close="true"
				@confirm="alertConfirm" @close="alertClose">
			</uni-popup-dialog>
		</uni-popup>


		<view class="cu-modal" :class="modalName=='Image'?'show':''">
			<view class="cu-dialog">
				<view style="height:250px;">
					<button @click="doCapture">点击拍照</button>
					<image :src="photoSrc"></image>
				</view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub  solid-left" @tap="hideModal">确认</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import Vue from 'vue';
	import {
		getToken
	} from '@/utils/auth';
	import common from '../../pages/common/common.js'
	var main, receiver, filter;
	var ScanDeviceClass = plus.android.importClass("android.device.ScanDevice");
	var scanDevice;
	export default {
		data() {
			return {
				modalName: null,
				photoSrc: '',
				userflag: false,
				productList: [],
				list: [],
				imageValue: [],
				salseId: '',
				baseUrl: getApp().globalData.config.baseUrl,
				userName: this.$store.state.user.name,
				orgId: getApp().globalData.config.orgId,
				id: '',
				index: '',
				status: '',
				lastStatus: '',
				customerScanNo: '',
				dataValue: '',
				total: 0,
				scanNum: 0,
				title: '',
			}
		},


		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			uni.showLoading({
				title: "加载中",
				mask: true
			});
			console.log(option);
			this.orgId = uni.getStorageSync('orgId');
			this.salseId = option.salseId;
			this.id = option.id;
			this.index = option.index;
			this.status = option.status;
			this.lastStatus = option.lastStatus;
			this.customerScanNo = option.customerScanNo;
			this.title = option.title;
		},

		onShow() {
			scanDevice = new ScanDeviceClass();
			scanDevice.openScan(); // 打开扫描
			scanDevice.setOutScanMode(0); // 扫描模式				
			this.initScan();
			this.registerScan();
		},

		mounted() {
			this.initQuery();
		},

		onBackPress(options) {
			var that = this;
			if (options.from === 'navigateBack') {
				return false;
			}
			//that.unregisterScan();
			//player.stop();
			let pages = getCurrentPages(); //获取所有页面栈实例列表
			let nowPage = pages[pages.length - 1]; //当前页页面实例
			let prevPage = pages[pages.length - 2]; //上一页页面实例
			prevPage.$vm.chooseTab(that.index);
			uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
				delta: 1
			});
			return true;
		},

		onHide: function() {
			this.unregisterScan();
		},

		destroyed: function() {
			this.unregisterScan();
		},

		methods: {
			initScan() {
				let _this = this;
				main = plus.android.runtimeMainActivity(); //获取activity  
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				filter = new IntentFilter();
				filter.addAction("scan.rcv.message"); // 换你的广播动作  
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let code = intent.getByteArrayExtra('barocode');
						let codeStr = common.utf8ByteToUnicodeStr(code);
						scanDevice.stopScan(); // 停止扫描	
						if (_this.status == '2') {
							uni.showToast({
								title: '任务已挂起，请先恢复',
								icon: 'none',
								duration: 3000
							});
							return;
						}

						if (_this.status == '3') {
							uni.showToast({
								title: '任务已完成，不能修改',
								icon: 'none',
								duration: 3000
							});
							return;
						}

						if ((_this.lastStatus != "3" && _this.lastStatus != "4") && (_this.customerScanNo ==
								null || _this.customerScanNo == '')) {
							_this.customerScanNo = codeStr;
							_this.dataValue = codeStr;
						} else {
							_this.updateData(codeStr);
							_this.reduceData(codeStr);
						}

					}
				});
			},

			initQuery() {
				var that = this;
				that.orgId = uni.getStorageSync('orgId');
				let token = getToken();
				uni.request({
					// url:that.baseUrl+'/system/loading/salseId',
					url: that.baseUrl + '/system/loading/salseId1',
					data: {
						salseId: that.salseId,
						orgId: that.orgId,
						userName: that.userName
					},
					method: 'POST',
					header: {
						'authorization': token
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						if (res.data.code == '200') {
							that.list = res.data.data;
							that.total = that.list.length;
							if ((that.lastStatus != "3" && that.lastStatus != "4") && (that.customerScanNo ==
									null || that.customerScanNo == '')) {
								that.$refs.alertDialog.open();
							} else {
								that.productList = that.list;
							}
							that.countNum();
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
							return;
						}
					}
				})
			},

			countNum() {
				var that = this;
				var count = 0;
				for (var i = 0; i < that.list.length; i++) {
					if (that.list[i].flag == 'true') {
						count = count + 1;
					}
				}
				that.scanNum = count;
				uni.setNavigationBarTitle({
					title: that.title.split('-')[1] + '(' + that.scanNum + '/' + that.total + ')'
				});
			},

			updateData(codeStr) {
				var that = this;
				if (that.userflag) {
					return;
				}
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				var symbol = 0;
				var data = '';
				var result = common.scanCode(codeStr);
				if (result[0] != "T") {
					uni.showToast({
						title: '请正确扫描托码',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				for (var i = 0; i < that.productList.length; i++) {
					data = that.productList[i];
					if (data.attr1 == result[1]) {
						if (data.flag != 'true') {
							symbol = 1;
						} else {
							symbol = 2;
						}
						break;
					}
				}
				uni.hideLoading();
				if (symbol == '1') {
					// data.flag = 'true';					
					// that.countNum();
					// that.prompt();
					uni.request({
						url: that.baseUrl + '/system/loading/uprecord',
						data: {
							content: result[1],
							orgId: that.orgId,
							flag: "true"
						},
						method: 'POST',
						header: {
							'authorization': getToken()
						},
						dataType: 'json',
						success: (res) => {
							console.log(res)
							//隐藏加载框
							uni.hideLoading();
							if (res.data.code == '200') {
								that.prompt();
								that.initQuery();
							} else if (res.data.code == '50000') { //20240205判断组托计划锁定
								uni.showToast({
									duration: 4000,
									icon: 'none',
									title: '该组托计划正在做变更已被锁定,不允许操作!'
								})
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 3000
								});
								return;
							}
						}
					})
				} else if (symbol == '2') {
					uni.showToast({
						title: '此托码已扫描',
						icon: 'none',
						duration: 5000
					});
					return;
				} else {
					uni.showToast({
						title: '此托码不存在',
						icon: 'none',
						duration: 5000
					});
					return;
				}
			},

			reduceData(codeStr) {
				var that = this;
				if (!that.userflag) {
					return;
				}
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				var symbol = false;
				var data = "";
				var result = common.scanCode(codeStr);
				if (result[0] != "T") {
					uni.showToast({
						title: '请正确扫描托码',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				for (var i = 0; i < that.productList.length; i++) {
					data = that.productList[i];
					if (data.attr1 == result[1]) {
						symbol = true;
						break;
					}
				}
				uni.hideLoading();
				if (symbol) {
					// data.flag = 'false';
					// that.prompt();
					// that.countNum();
					uni.request({
						url: that.baseUrl + '/system/loading/uprecord',
						data: {
							content: result[1],
							orgId: that.orgId,
							flag: "false"
						},
						method: 'POST',
						header: {
							'authorization': getToken()
						},
						dataType: 'json',
						success: (res) => {
							console.log(res)
							//隐藏加载框
							uni.hideLoading();
							if (res.data.code == '200') {
								that.prompt();
								that.initQuery();
							} else if (res.data.code == '50000') { //20240205判断组托计划锁定
								uni.showToast({
									duration: 4000,
									icon: 'none',
									title: '该组托计划正在做变更已被锁定,不允许操作!'
								})
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 3000
								});
								return;
							}
						}
					})
				} else {
					uni.showToast({
						title: '此托码不存在',
						icon: 'error',
						duration: 2000
					});
					return;
				}
			},

			registerScan() {
				main.registerReceiver(receiver, filter);
			},

			unregisterScan() {
				main.unregisterReceiver(receiver);
			},
			getdetail(e) {
				var that = this
				uni.request({
					url: that.baseUrl + '/system/loading/salseId1ChildList',
					data: e,
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						if (res.data.code == '200') {
							console.log(res.data.data.childList)
							var childList = encodeURIComponent(JSON.stringify(res.data.data.childList));
							uni.navigateTo({
								url: '/pages/wm_truck/wm_truck_loading_line?attr1=' + e.attr1 +
									'&detailList=' + childList,
							})
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
							return;
						}
					}
				})
			},

			goto(item) {

				console.log(item)
				this.getdetail(item)
				// var childList = encodeURIComponent(JSON.stringify(item.childList));
				// uni.navigateTo({
				// 	url: '/pages/wm_truck/wm_truck_loading_line?attr1='+item.attr1+'&detailList='+childList,
				// })
			},

			reduceProduct() {
				var that = this;
				if (that.status == '2') {
					uni.showToast({
						title: '任务已挂起，请先恢复',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				if (that.status == '3') {
					uni.showToast({
						title: '任务已完成，不能修改',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (that.userflag) {
					if (that.userflag) {
						that.userflag = false;
					} else {
						that.userflag = true;
					}
				} else {
					uni.showModal({
						title: '提示',
						content: '是否进行卸下托盘操作？',
						success: function(res) {
							if (res.confirm) {
								if (that.userflag) {
									that.userflag = false;
								} else {
									that.userflag = true;
								}
							} else if (res.cancel) {
								return;
							}
						}
					})
				}
			},

			sumbit(e) {
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				if (this.status == '2') {
					uni.hideLoading();
					uni.showToast({
						title: '任务已挂起，请先恢复',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				if (this.status == '3') {
					uni.hideLoading();
					uni.showToast({
						title: '任务已完成，不能修改',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				var num = 0;
				for (var i = 0; i < this.productList.length; i++) {
					var data = this.productList[i];
					if (data.flag == 'true') {
						num = num + 1;
					}
				}
				uni.hideLoading();
				if (num != this.productList.length) {
					uni.showToast({
						title: '校验尚未完成，不能提交',
						icon: 'none',
						duration: 3000
					});
					return;
				} else {
					this.modalName = e.currentTarget.dataset.target;
				}

			},

			hideModal(e) {
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				this.modalName = null;
				//先掉超越，推U9，然后掉邦邦更改代办任务状态
				uni.request({
					url: this.baseUrl + '/system/loading/jpg',
					data: {
						jpg: this.photoSrc,
						orgId: this.orgId,
						salseId: this.salseId
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						if (res.data.code == '200') {
							this.updateTask();
							this.toU9();
						} else if (res.data.code == '50000') { //20240205判断组托计划锁定
							uni.hideLoading();
							uni.showToast({
								duration: 4000,
								icon: 'none',
								title: '该组托计划正在做变更已被锁定,不允许操作!'
							})
						} else {
							uni.hideLoading();
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
						}

					}
				})
			},

			// 往u9推送出库单
			toU9() {
				var tip = this.title.split("-")[1];
				uni.request({
					url: this.baseUrl + '/system/loading/toU9',
					data: {
						userName: this.userName,
						orgId: this.orgId,
						salseId: this.salseId
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						if (res.data.code == '200') {
							uni.showToast({
								title: '装车单' + tip + '推送成功',
								icon: 'none',
								duration: 5000
							});
						} else {
							uni.showToast({
								title: '装车单' + tip + '推送U9失败',
								icon: 'none',
								duration: 5000
							});
						}

					}
				})
			},

			updateTask() {
				var that = this;
				uni.request({
					url: that.baseUrl + '/system/wmsbacklog/update',
					data: {
						id: that.id,
						status: '3',
						orgId: that.orgId,
						startTime: '',
						endTime: new Date().toISOString().slice(0, 10),
						userName: that.userName
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						uni.hideLoading();
						if (res.data.code == '200' || res.data.code == 200) {
							uni.showToast({
								title: '装车成功并且代办任务已完成',
								icon: 'none',
								duration: 2000
							});
							//that.unregisterScan();
							//player.stop();
							setTimeout(function() {
								let pages = getCurrentPages(); //获取所有页面栈实例列表
								let nowPage = pages[pages.length - 1]; //当前页页面实例
								let prevPage = pages[pages.length - 2]; //上一页页面实例
								prevPage.$vm.chooseTab(that.index);
								uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
									delta: 1
								});
							}, 1000);
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}

					},
				})
			},

			doCapture() {
				var that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						// 预览图片
						//this.uploadFile(res.tempFilePaths[0]);
						uni.uploadFile({
							url: that.baseUrl + '/common/upload1', //服务器地址
							fileType: "image", //ZFB必填,不然报错
							filePath: res.tempFilePaths[0], //这个就是我们上面拍照返回或者先中照片返回的数组
							name: 'file',
							header: {
								'authorization': getToken()
							},
							success: (uploadFileRes) => {
								let imgData = JSON.parse(uploadFileRes.data)
								that.photoSrc = imgData.url;
							}
						});
					}
				});
			},

			alertConfirm(value) {
				if (this.dataValue == null || this.dataValue == '') {
					uni.showToast({
						title: '请扫描客户手中的二维码',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				//显示加载框
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				this.queryLoadData(value);
			},

			queryLoadData(value) {
				var that = this;
				uni.request({
					url: that.baseUrl + "/system/loading/truckId",
					data: {
						orgId: that.orgId,
						userName: that.userName,
						packageNo: value,
						type: "compare"
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						console.log(res)
						console.log('res.data.msg' + res.data.msg);
						console.log('that.salseId' + that.salseId);
						if (res.data.code == '200' || res.data.code == 200) {
							if (res.data.msg == that.salseId) {
								that.productList = that.list;
								that.$refs.alertDialog.close();
								uni.hideLoading();
							} else {
								uni.hideLoading();
								that.customerScanNo = '';
								uni.showToast({
									title: '此装车任务与客户手中的任务不对应',
									icon: 'none',
									duration: 5000
								});
								return;
							}
						} else {
							that.customerScanNo = '';
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 5000
							});
							return;
						}
					},
				})
			},

			prompt(type) {
				var innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '/static/mp3/success.mp3';
				//innerAudioContext.play();//铃声文件的路径
				//innerAudioContext.stop();
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				innerAudioContext.onPause(function() {
					console.log('end');
					innerAudioContext.destroy()
				})
			},

			alertClose() {
				// if(this.dataValue == null || this.dataValue == ''){
				// 	uni.showToast({
				// 		title: '请扫描客户手中的二维码',
				// 		icon: 'none',
				// 		duration: 5000
				// 	});
				// 	return;
				// }
				// this.$refs.alertDialog.close();	
				this.dataValue = '';
				this.customerScanNo = '';
			},

		}
	}
</script>

<style lang="less">
	page {
		width: 100%;
		height: 100%;
	}


	.scrool-page {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	.header-cont {
		width: 100%;
		height: 110rpx;
		line-height: 100rpx;
		text-align: center;
		// background: red;
	}

	.list-cont {
		flex: 1;
		position: relative;

		.scrool-more {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}

		.list {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #e0e0e0;

		}
	}


	.footer {
		color: #fff;
		line-height: 100rpx;
		flex: 0 0 100rpx;
		/* 不放大不缩小固定100rpx */
	}
</style>